<template>
  <div class="detail-header">
    <el-page-header @back="onBack">
      <template #content>
        <div class="flex items-center">
          <el-avatar class="mr-3" :size="50" :src="clubDetail.club_avatar" />
          <span
            class="text-sm mr-2 club-name"
            style="color: var(--el-text-color-regular)"
          >
            {{ clubDetail.name }}
          </span>
          <el-tag>active</el-tag>
        </div>
      </template>
      <el-descriptions :column="10" size="large" class="mt-4">
        <el-descriptions-item label="社团社长">{{
          clubDetail.leaderName
        }}</el-descriptions-item>
        <el-descriptions-item label="社长电话">{{
          clubDetail.contact_info
        }}</el-descriptions-item>
        <el-descriptions-item label="社长邮箱">{{
          clubDetail.email
        }}</el-descriptions-item>
        <el-descriptions-item label="社团创建时间">
          {{ formatUTC(clubDetail.created_at) }}
        </el-descriptions-item>
      </el-descriptions>
      <p class="mt-4 text-sm">社团描述 :{{ clubDetail.description }}</p>
    </el-page-header>
  </div>
  <div class="search">
    <!-- 1.输入搜索关键字的表单 -->
    <el-form :model="searchForm" ref="formRef" label-width="80px" size="large">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="社团成员" prop="name">
            <el-input
              v-model="searchForm.name"
              placeholder="输入要查询的社团成员名字"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择查询的状态"
              style="width: 100%"
            >
              <el-option label="激活" value="active" />
              <el-option label="待审核" value="pending" />
              <el-option label="未激活" value="rejected" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 2.重置和搜索的按钮 -->
    <div class="btns">
      <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
      <el-button icon="Search" type="primary" @click="handleQueryClick"
        >查询</el-button
      >
    </div>
  </div>
  <div class="detail-content">
    <div class="content">
      <div class="header">
        <h3 class="title">社团成员</h3>
        <!-- <el-button type="primary" @click="handleNewUserClick"
          >添加成员</el-button
        > -->
      </div>

      <div class="table">
        <el-table :data="clubMemebrs" border style="width: 100%">
          <el-table-column align="center" type="selection" width="50px" />
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="60px"
          />

          <el-table-column
            align="center"
            label="用户名"
            prop="name"
            width="150px"
          />

          <el-table-column
            align="center"
            label="昵称"
            prop="nickname"
            width="150px"
          />
          <el-table-column align="center" label="用户头像" prop="avatar_url">
            <template #default="scope">
              <img style="width: 50px" :src="scope.row.avatar_url" alt="" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="加入时间" prop="join_date">
            <template #default="scope">
              {{ formatUTC(scope.row.join_date) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="用户角色" prop="role">
            <template #default="scope">
              {{ scope.row.role === 'leader' ? '社长' : '普通成员' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="成员状态" prop="status">
            <template #default="scope">
              <el-button size="small" type="default">
                {{ returnStatus(scope) }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="200px">
            <template #default="scope">
              <el-button
                size="small"
                icon="Edit"
                type="primary"
                text
                v-if="isShowEditLeader(scope)"
                @click="setLeader(scope.row)"
              >
                设为社长
              </el-button>
              <el-button
                size="small"
                icon="check"
                type="success"
                text
                v-if="isShowAgree(scope)"
                @click="agreeAddClub(scope.row)"
              >
                同意
              </el-button>
              <el-button
                size="small"
                icon="close"
                type="warning"
                text
                v-if="isShowReject(scope)"
                @click="rejectAddClub(scope.row)"
              >
                拒绝
              </el-button>
              <el-button
                size="small"
                icon="Delete"
                type="danger"
                text
                @click="deleteClubMember(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="clubMemebersTotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'

import useClubStore from '@/store/main/club/club'
import type { IClubMember } from '@/store/main/club/type'
import { formatUTC } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
const route = useRoute()
const router = useRouter()
const clubStore = useClubStore()
// 获取分页数据
const currentPage = ref(1)
const pageSize = ref(10)
// 获取传递过来的信息根据id查询
const { id } = route.query
// 搜索值
const searchForm = reactive({
  name: '',
  status: 'active'
})

fetchClubDeatilData()

const { clubMemebrs, clubDetail, clubMemebersTotalCount } =
  storeToRefs(clubStore)
function fetchClubDeatilData(name?: string, status?: string) {
  // 1.获取offset/size
  const limit = pageSize.value
  const offset = (currentPage.value - 1) * limit
  clubStore.getClubDetaiByIdAction(Number(id))
  clubStore.getClubMemberByClubIdAction(Number(id), limit, offset, name, status)
}
// 初始化searchForm
function resetSearchForm() {
  searchForm.name = ''
  searchForm.status = 'active'
}

// 返回上一步
function onBack() {
  router.back()
}
/** 渲染操作 */
// 判断是否显示设为设置
function isShowEditLeader(scope: any) {
  return (
    scope.row.user_id !== clubDetail.value.leader_id &&
    scope.row.status === 'active'
  )
}
// 判断是否同意
function isShowAgree(scope: any) {
  return scope.row.status !== 'active'
}

// 判断是否拒绝
function isShowReject(scope: any) {
  return scope.row.status === 'pending'
}
// 渲染不同的状态
function returnStatus(scope: any) {
  let status = ''
  if (scope.row.status === 'active') {
    status = '激活'
  } else if (scope.row.status === 'pending') {
    status = '待审核'
  } else {
    status = '未激活'
  }
  return status
}

/** 搜索操作 */
// 查询操作
function handleQueryClick() {
  fetchClubDeatilData(searchForm.name, searchForm.status)
  ElMessage({
    message: '查询成功',
    type: 'success',
    duration: 1000
  })
}
// 重置操作
function handleResetClick() {
  fetchClubDeatilData()
  resetSearchForm()
  ElMessage({
    message: '重置成功',
    type: 'success',
    duration: 1000
  })
}

/** 添加成员操作 */

/**对成员进行操作 */
// 设为社长
async function setLeader(row: IClubMember) {
  const newClubInfo = clubDetail.value
  newClubInfo.leaderName = row.name
  ElMessageBox.confirm(`确认修改社长吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await clubStore.editClubDataAtion(Number(id), newClubInfo)
    ElMessage({
      message: '修改社长成功',
      type: 'success',
      duration: 1000
    })
    fetchClubDeatilData()
    resetSearchForm()
  })
}
// 同意参加社团
async function agreeAddClub(row: IClubMember) {
  const { user_id } = row
  await clubStore.setClubMemberStatusAction(Number(id), user_id, 'active')
  ElMessage({
    message: '审核成功',
    type: 'success',
    duration: 1000
  })
  fetchClubDeatilData(searchForm.name, searchForm.status)
}

// 拒绝参加社团
async function rejectAddClub(row: IClubMember) {
  const { user_id } = row
  await clubStore.setClubMemberStatusAction(Number(id), user_id, 'rejected')
  ElMessage({
    message: '审核成功',
    type: 'success',
    duration: 1000
  })
  fetchClubDeatilData(searchForm.name, searchForm.status)
}

// 删除成员
async function deleteClubMember(row: IClubMember) {
  const { user_id, status } = row
  ElMessageBox.confirm(`确认删除这个成员吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if (status !== 'rejected') {
      await clubStore.setClubMemberStatusAction(Number(id), user_id, 'rejected')
      ElMessage({
        message: '移除成员成功',
        type: 'success',
        duration: 1000
      })
    } else {
      await clubStore.deleteClubMemebrAction(Number(id), user_id)
      ElMessage({
        message: '删除成员成功',
        type: 'success',
        duration: 1000
      })
    }

    fetchClubDeatilData(searchForm.name, searchForm.status)
  })
}

/**分页器 */
function handleSizeChange() {
  fetchClubDeatilData(searchForm.name, searchForm.status)
}
function handleCurrentChange() {
  fetchClubDeatilData(searchForm.name, searchForm.status)
}
</script>

<style scoped lang="less">
.detail-header {
  background-color: #fff;
  padding: 20px;
  .club-name {
    margin-left: 10px;
    margin-right: 10px;
    vertical-align: middle;
  }
}
.search {
  background-color: #fff;
  margin-top: 20px;

  .el-form-item {
    padding: 20px 30px;
    margin-bottom: 0;
  }

  .btns {
    text-align: right;
    padding: 0 50px 10px 0;

    .el-button {
      height: 36px;
    }
  }
}
.detail-content {
  .content {
    margin-top: 20px;
    padding: 20px;
    background-color: #fff;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 10px;

    .title {
      font-size: 22px;
    }
  }

  .table {
    :deep(.el-table__cell) {
      padding: 12px 0;
    }

    .el-button {
      margin-left: 0;
      padding: 5px 8px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
}
</style>
